package cn.itsource.org.service.impl;

import cn.itsource.basic.service.impl.BaseServiceImpl;
import cn.itsource.basic.util.PageList;
import cn.itsource.basic.util.RedisService;
import cn.itsource.basic.util.TreeUtil;
import cn.itsource.org.domain.Chart;
import cn.itsource.org.domain.ChartResult;
import cn.itsource.org.domain.Department;
import cn.itsource.org.mapper.DepartmentMapper;
import cn.itsource.org.query.DepartmentQuery;
import cn.itsource.org.service.IDepartmentService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 万能键 alt + enter
 */
@Service //交给spring管理
//事务支持
@Transactional(propagation = Propagation.SUPPORTS)
public class DepartmentServiceImpl extends BaseServiceImpl<Department, DepartmentQuery> implements IDepartmentService {

    @Autowired
    private RedisService redisService;

    /**
     * 注入mapper层对象
     */
    @Autowired
    private DepartmentMapper departmentMapper;


    @Override
    @Transactional //就近原则
    public void saveOrUpdate(Department department) {

        //import org.apache.commons.lang3.StringUtils;
        //最简单的参数验证
      /*  if (StringUtils.isBlank(department.getName())){
            throw new RuntimeException("部门名称必填");
        }

        if (StringUtils.isBlank(department.getSn())){
            throw new RuntimeException("部门编号必填");
        }
*/

        //新增
        if (department.getId() == null){


            //任何字段都会被操作
            //departmentMapper.insert(department);

            //只有设置了值的字段才会被新增进去
            departmentMapper.insertSelective(department);

            //调用方法
            makeParentDept(department);

            //4.修改这个对象
            departmentMapper.updateByPrimaryKey(department);

        }else {
            //调用方法
            makeParentDept(department);

            //根据主键修改,只有设置了值的字段才会被新增进去
            departmentMapper.updateByPrimaryKey(department);


        }

    }

    /**
     * ctrl + alt + m
     * @param department
     */
    private void makeParentDept(Department department) {
        Long[] parentIds = department.getParentIds();//3 8 10  // /3/8/10
        if (parentIds != null && parentIds.length > 0) {

            //1.设置parentId的值
            Long parentId = parentIds[parentIds.length - 1];
            department.setParentId(parentId);

            //2.循环  用得快捷提示:输入iter
            StringBuilder dirPath = new StringBuilder("");
            for (Long id : parentIds) {
                dirPath.append("/").append(id);
            }
            //3.加上自己的主键id值
            dirPath.append("/").append(department.getId()); //3/8/10/203
            department.setDirPath(dirPath.toString());

        } else {
            department.setParentId(null);
            department.setDirPath("/" + department.getId());
        }
    }



    @Override
    public PageList<Department> findPage(DepartmentQuery departmentQuery) {

        //分页查询
        //1.分页工具包
        PageHelper.startPage(departmentQuery.getPage(), departmentQuery.getSize());

        long l = System.currentTimeMillis();
        //redis的key 包含高级查询的条件
        String key = "dept_list_"+departmentQuery.getPage()+"_"+departmentQuery.getSize()+"_"+departmentQuery.getKeyword()+"_"+departmentQuery.getManagerId()+"_"+departmentQuery.getParentId();

        //2.从redis中查询数据
        PageList<Department> redisPageList = redisService.getKeyObjectValue(key, PageList.class);
        if (redisPageList != null){
            long l1 = System.currentTimeMillis();
            System.out.println("redis拿到数据执行的毫秒数:"+(l1-l));
            return redisPageList;
        }

        //2.调用方法
        List<Department> departments = departmentMapper.findPage(departmentQuery);

        //3.封装一个pageInfo对象
        PageInfo<Department> pageInfo = new PageInfo<>(departments);

        //4.封装自定义的分页对象
        PageList<Department> pageList = new PageList<>(pageInfo.getTotal(), pageInfo.getList());


        long l1 = System.currentTimeMillis();
        System.out.println("数据库拿到数据执行的毫秒数:"+(l1-l));

        //如果第一次key最新的,存
        redisService.setStringKeyAndValue(key,pageList);

        return pageList;
    }

    @Override
    public List<Department> findParentDepts() {
        return departmentMapper.findParentDepts();
    }

    @Override
    public List<Department> treeList() {

        //1.查询所有的部门对象集合
        List<Department> departments = departmentMapper.selectAll();

        //2.使用工具类的方法
        List<Department> list = TreeUtil.getTree(departments);

        return list;
    }

    @Override
    public ChartResult findChartData() {
        //1.查询部门分组数据
        List<Chart> charts = departmentMapper.findChartData();

        //2.封装两个list
        //map:映射,每一个对象通过getName拿到的值,collect:收集成一个List类型
        List<String> nameList = charts.stream().map(Chart::getName).collect(Collectors.toList());
        List<Integer> numList = charts.stream().map(Chart::getNum).collect(Collectors.toList());

        //3.封装对象
        ChartResult chartResult = new ChartResult();

        chartResult.setNames(nameList);
        chartResult.setNums(numList);

        return chartResult;
    }

}
